package com.xianniu.ltc.aspect;

import cn.devezhao.persist4j.Query;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.xianniu.ltc.mapper.TRbshangji1Mapper;
import com.xianniu.ltc.model.entity.TRbshangji1DTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.soap.SAAJResult;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author wangruijie
 *
 */
@Slf4j
@Aspect
@Component
public class DeleteRecordBeforeAspect {

    @Resource
    private TRbshangji1Mapper rbshangji1Mapper;
    //拦截指定的方法,GeneralOperatingController.delete 这个方法
    @Pointcut("execution(public * com.rebuild.web.general.GeneralOperatingController.delete(..))")
    public void excuteService() {

    }

    //执行方法前的拦截方法
    @Before("excuteService()")
    public void doBeforeMethod(JoinPoint joinPoint) {
        log.info("前置通知，删除超能保商机类型的商机时，同步删除超能保商机实体的数据");
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        String recordId = (String) obj[0];
        doDeleteRecord(recordId);
    }

    /**
     * 通过商机ID查询商机编号，类型
     * @param idList
     * @return
     */
    public Object doDeleteRecord(String idList){
        int i = 0;
        String[] l = idList.split(",");
        for (String s : l){
            String sql = String.format("select shangjibianhao,shangjileixing from rbshangji4 where rbshangji4Id = ? and tenantCode = ? ");
            Query shangJi = Application.createQueryNoFilter(sql)
                    .setParameter(1, ID.valueOf(s))
                    .setParameter(2, UserContextHolder.getTenant());

            Object[] result = shangJi.unique();
            if (result != null){
                ID leix = (ID) result[1];
                // 如果是超能保类型的商机，则同步删除超能保商机
                if (String.valueOf(leix).equals("019-01813cebc87b0174")){
                    QueryWrapper<TRbshangji1DTO> queryWrapper =new QueryWrapper<>();
                    queryWrapper.eq("SHANGJIBIANHAO", result[0]);
                    log.info("通过同步商机编号，删除对应超能保商机：{}", result[0]);
                    i = rbshangji1Mapper.delete(queryWrapper);
                    i ++;
                    log.info("通过同步商机编号，删除对应超能保商机个数：{}", i);
                }
            }
        }
        return i;
    }
}